﻿using System;
using System.Collections.Generic; 
using System.Linq;
using System.Text;
using System.Web.UI;

namespace GoodStuff.Web.Controls
{
    /// <summary>
    /// Generic footer control to embed customizable statistics trackers. All tracker scripts
    /// and replacements can be configured using the web.config/trackerConfiguration
    /// </summary>
    public class Trackers : Control
    {       
        protected override void Render(HtmlTextWriter writer)
        {
            // TODO: Cache the include files.
            //iterate over all configured trackers and render each one.
            TrackerConfiguration config = ConfigurationHelper.GetSection<TrackerConfiguration>();

            foreach (var entry in config.Entries)
            {
                string tracker = Cached.Get<string>("Tracker" + entry.Include, "Trackers", TimeSpan.FromHours(8), () =>
                    {
                        string include = System.IO.File.ReadAllText(Page.MapPath(entry.Include));
                        foreach (var replacement in entry.Replacements)
                        {
                            include = include.Replace(replacement.Key, replacement.Value);
                        }
                        return include;
                    });

                writer.Write(tracker);
            }
        }
    }
}
